import logging
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import MenuModel, PermissionsModel

logger = logging.getLogger('erp')

methods = {'POST': '新增', 'GET': '查询', 'PUT': '修改', 'DELETE': '删除', 'PATCH': '局部修改'}


@receiver(post_save, sender=MenuModel)
def create_menu_permissions(sender, instance, created, **kwargs):
    """
    创建信号监控函数，信号接收者收到之后自动触发，创建菜单资源对应的权限
    """
    if created:
        logger.info("创建菜单资源对应权限")
        if isinstance(instance, MenuModel):
            # 判断如果他没有父菜单，那么menu就是功能亩快菜单对象
            if not instance.parent:
                permission = PermissionsModel.objects.create(name=instance.name + '的权限', is_menu=True)
                # 关联起来
                permission.menu = instance
                # 保存
                permission.save()
            else:  # 那么他就是接口
                for method in methods.keys():
                    permission = PermissionsModel.objects.create(
                        name=f'{instance.name}的{methods.get(method)}的权限!', is_menu=False, method=method,
                        path=instance.url)
                    # logger.info(permission.name)
                    permission.menu = instance
                    permission.save()
        else:
            logger.warning('当前对象不是MenuModel模型，所以不需要创建对应的权限数据!')
